/**
 * <p>Title: ServiceZMCP09.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张志芳
 * @version 1.0
 * <pre>Histroy:
 *          2011-10-24 下午03:31:07  张志芳  Create
 *</pre>
 */
package com.baosight.sczx.zm.cp.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.StaticBlocks;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.cp.ProducePlan;
import com.baosight.sczx.common.zm.cInterface.cp.ProducePlanOther;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlan;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlanFT;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlanGLAZ;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlanZC;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlanZK;
import com.baosight.sczx.zm.cp.domain.ZMCPProfessionalPlan;

/**
 * 抽采专业计划
 * <p>
 * Title: ServiceZMCP14.java
 * </p>
 */
public class ServiceZMCP14 extends ServiceEPBase {

	/**
	 * <p>
	 * Function: initLoad
	 * </p>
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");// 如果不加这个，翻页的统计和显示是错误的
		EiInfo outInfo = this.query(inInfo);
		outInfo.addBlock(StaticBlocks.getPlanMonth("cmes.cp.planMonth", true));
		outInfo.addBlock(StaticBlocks.getPlanStatus("cmes.cp.planStatus", true));
		return outInfo;
	}

	/**
	 * <p>
	 * Function: query
	 * </p>
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		StaticTools.setQueryParameters(inInfo, "fdPlanType", "抽采计划", true);
		StaticTools.setQueryParameters(inInfo, "fdMiningId", UserSession.getInSessionProperty("miningCode"), true);
		EiInfo outInfo = super.query(inInfo, "ZMCPProfessionalPlan.query", new ZMCPProfessionalPlan());
		outInfo.addBlock(Department.getInstance().getMiningDepts("cmes.cp.department", "orgCode", "orgName", false, UserSession.getInSessionProperty("miningCode").toString()));
		outInfo.addBlock(StaticBlocks.getBlockData("cmes.cs.engineeringClass", new String[] { "打钻", "抽采", "管路安装", "水力冲孔" }, new String[] { "打钻", "抽采", "管路安装", "水力冲孔" }, false));// 通防工程类型
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.holeType"));
		outInfo.addBlock(StaticBlocks.getPlanMonth("cmes.cp.planMonth", true));
		return outInfo;
	}

	/**
	 * <p>
	 * Function: insert
	 * </p>
	 * <p>
	 * Description: 新增
	 * </p>
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) {
		EiInfo out = new EiInfo();
		ZMCPProfessionalPlan _dom = new ZMCPProfessionalPlan();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();

		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			Map<String, String> params = new HashMap<String, String>();
			params.put("fdPlanType", _dom.getFdPlanType());
			params.put("fdPlanYear", _dom.getFdPlanYear());
			params.put("fdPlanMonth", _dom.getFdPlanMonth());
			params.put("fdMiningId", UserSession.getInSessionProperty("miningCode").toString());
			boolean validate = this.validate(_dom, "ZMCPProfessionalPlan.insertValidate", params, "insert");
			if (validate) {
				out = this.query(inInfo);
				out.setMsg("该年月的抽采专业计划已经存在！");
				return out;
			} else {
				String fdCreateDepartmentId = _dom.getFdCreateDepartmentId();
				
				_dom.setFdKeyId(TablePk.getInstance().getNextValue("T_CP_PROFESSIONALPLAN"));
				_dom.setFdCreateDepartment(Department.getInstance().getDepartmentNameById(fdCreateDepartmentId));
				_dom.setFdMiningId(UserSession.getInSessionProperty("miningCode").toString());
				_dom.setFdMiningName(UserSession.getInSessionProperty("miningName").toString());
				_dom.setFdCreator(UserSession.getInSessionProperty("UserCname").toString());
				_dom.setFdCreatorId(UserSession.getUserId().toString());
				_dom.setFdCreateDepartment(UserSession.getInSessionProperty("orgName").toString());
				_dom.setFdCreateDepartmentId(UserSession.getInSessionProperty("orgCode").toString());
				_dom.setFdYmSum(new BigDecimal(_dom.getFdYmSum().floatValue()*10000));
				//如果有附件上传功能的模块，需要增加以下生成docid方法。生成规则调用统一的方法。修改时不用管docid，也就是docid一旦生成不能修改。除非删除
				_dom.setFdDocId(StaticTools.getDocId());
				this.dao.insert("ZMCPProfessionalPlan.insert", _dom);
			}

		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;
	}

	/**
	 * <p>
	 * Function: update
	 * </p>
	 * <p>
	 * Description: 修改
	 * </p>
	 */
	@SuppressWarnings("unused")
	@Override
	public EiInfo update(EiInfo inInfo) {
		EiInfo out = new EiInfo();
		ZMCPProfessionalPlan _dom = new ZMCPProfessionalPlan();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		Map<String, String> params = new HashMap<String, String>();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			params.put("fdProfessionalplanId", _dom.getFdKeyId());
			boolean validate = this.validateModify(inInfo, "ZMCPProducePlanZC.query", params, "update");
			boolean validate1 = this.validateModify(inInfo, "ZMCPProducePlanZK.query", params, "update");
			boolean validate2 = this.validateModify(inInfo, "ZMCPProducePlanGLAZ.query", params, "update");
//			if (validate || validate1 || validate2) {
//				return inInfo;
//			} else {
				params.put("fdPlanYear", _dom.getFdPlanYear());
				params.put("fdPlanMonth", _dom.getFdPlanMonth());
				params.put("fdPlanType", "抽采计划");
				params.put("fdMiningId", _dom.getFdMiningId());
				params.put("fdMiningName", _dom.getFdMiningName());
				params.put("fdKeyId", _dom.getFdKeyId());
				boolean validate3 = this.validate(_dom, "ZMCPProfessionalPlan.updateValidate", params, "update");
				if (validate3) {
					out = this.query(inInfo);
					out.setMsg("该年月的抽采专业计划已经存在！");
					return out;
				} else {
					_dom.setFdCreator(UserSession.getInSessionProperty("UserCname").toString());
					_dom.setFdCreatorId(UserSession.getUserId().toString());
					_dom.setFdCreateDepartment(UserSession.getInSessionProperty("orgName").toString());
					_dom.setFdCreateDepartmentId(UserSession.getInSessionProperty("orgCode").toString());
					_dom.setFdYmSum(new BigDecimal(_dom.getFdYmSum().floatValue()*10000));
					this.dao.update("ZMCPProfessionalPlan.update", _dom);
				}
//			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;
	}

	/**
	 * <p>
	 * Function: delete
	 * </p>
	 * <p>
	 * Description: 删除
	 * </p>
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) {

		EiInfo outInfo = new EiInfo();
		ZMCPProducePlanFT _dom = new ZMCPProducePlanFT();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();

		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			// 判断是否有明细
			Map<String, String> params = new HashMap<String, String>();
			params.put("fdProfessionalplanId", _dom.getFdKeyId());
			boolean validate = this.validateModify(inInfo, "ZMCPProducePlanZC.query", params, "delete");
			boolean validate1 = this.validateModify(inInfo, "ZMCPProducePlanZK.query", params, "delete");
			boolean validate2 = this.validateModify(inInfo, "ZMCPProducePlanGLAZ.query", params, "delete");
			if (validate || validate1 || validate2) {
				return inInfo;
			} else {

				this.dao.delete("ZMCPProfessionalPlan.delete", _dom);
			}
		}
		outInfo = this.query(inInfo);
		outInfo.setStatus(1);
		outInfo.setMsg("操作" + rowcount + "记录成功");
		return outInfo;
	}

	/**
	 * <p>
	 * Function: report
	 * </p>
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public EiInfo report(EiInfo inInfo) {
		String fdPlanYear = inInfo.getBlock("result").getCellStr(0, "fdPlanYear");
		String fdPlanMonth = inInfo.getBlock("result").getCellStr(0, "fdPlanMonth");
		String fdProfessionalplanId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");
		
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		_map.put("fdPlanStatus", "草拟");
		
		List result = this.dao.query("ZMCPProfessionalPlan.query", _map);
		//1.0 进度完成
		if (result == null || result.isEmpty()) {
			inInfo.setStatus(-1);
			inInfo = this.query(inInfo);
			inInfo.setMsg(fdPlanYear +"年"+ fdPlanMonth +"月计划已经上报或作废，不能上报！");
			return inInfo;
		}
		
		//2.0判断是否有明细
		Map map = new HashMap();
		map.put("fdProfessionalplanId", fdProfessionalplanId);
		List _listZC = dao.query("ZMCPProducePlanZC.query", map);
		List _listZK = dao.query("ZMCPProducePlanZK.query", map);
		List _listGLAZ = dao.query("ZMCPProducePlanGLAZ.query", map);
		
		if (_listZC.size() > 0 && _listZK.size() > 0 && _listGLAZ.size() > 0) {
			//3.0判断是否能上报
			String fdProduceplanId = ProducePlan.checkCanReport(inInfo);
			
			//4.0已经存在生产计划
			if(fdProduceplanId == null) {
				inInfo.getBlock("result").setCell(0, "fdPlanStatus", "作废");
				this.update(inInfo, "ZMCPProfessionalPlan.updatePlanStatus");
			}
			else {
				//生产计划不存在主表 或 主表为草拟
				inInfo.getBlock("result").setCell(0, "fdPulisherId", UserSession.getUserId());
				inInfo.getBlock("result").setCell(0, "fdPulisher", UserSession.getInSessionProperty("UserCname"));
				inInfo.getBlock("result").setCell(0, "fdPlanStatus", "上报");
				this.update(inInfo, "ZMCPProfessionalPlan.updatePlanStatus");
				
				//5.0clone明细表
				for(int i = 0; i < _listZC.size(); i++) {
					ZMCPProducePlanZC _plan = (ZMCPProducePlanZC)_listZC.get(i);
					String fdKeyId = TablePk.getInstance().getNextValue("T_CP_PRODUCEPLAN_ZC");
					_plan.setFdKeyId(fdKeyId);
					_plan.setFdProduceplanId(fdProduceplanId);
					
					dao.insert("ZMCPProducePlanZC.insert", _plan.toMap());
				}
				
				for(int i = 0; i < _listZK.size(); i++) {
					ZMCPProducePlanZK _plan = (ZMCPProducePlanZK)_listZK.get(i);
					String fdKeyId = TablePk.getInstance().getNextValue("T_CP_PRODUCEPLAN_ZK");
					_plan.setFdKeyId(fdKeyId);
					_plan.setFdProduceplanId(fdProduceplanId);
					
					dao.insert("ZMCPProducePlanZK.insert", _plan.toMap());
				}
				
				for(int i = 0; i < _listGLAZ.size(); i++) {
					ZMCPProducePlanGLAZ _plan = (ZMCPProducePlanGLAZ)_listGLAZ.get(i);
					String fdKeyId = TablePk.getInstance().getNextValue("T_CP_PRODUCEPLAN_GLAZ");
					_plan.setFdKeyId(fdKeyId);
					_plan.setFdProduceplanId(fdProduceplanId);
					
					dao.insert("ZMCPProducePlanGLAZ.insert", _plan.toMap());
				}
				//update生产计划表 -- 瓦斯抽采量
				String str = (String) inInfo.getBlock("result").getCell(0, "fdWscc");
				BigDecimal fdWscc = new BigDecimal(str);
				ZMCPProducePlan zp = new ZMCPProducePlan();
				zp.setFdPlanWsccl(fdWscc);
				zp.setFdKeyId(fdProduceplanId);
				dao.insert("ZMCPProfessionalPlan.changeWsccl",zp.toMap());
			}
		}
		else {
			inInfo.setStatus(-1);
			inInfo.setMsg("上报的专业计划中有的没有明细，请添加明细后上报！");
			return inInfo;
		}
		
		EiInfo outInfo = this.query(inInfo);
		return outInfo;
	}

	@SuppressWarnings("rawtypes")
	public EiInfo goback(EiInfo inInfo) {
		//1.0判断当月生产计划是否已经生效
		String fdPlanYear = inInfo.getBlock("result").getCellStr(0, "fdPlanYear");
		String fdPlanMonth = inInfo.getBlock("result").getCellStr(0, "fdPlanMonth");
		String fdMiningId = inInfo.getBlock("result").getCellStr(0, "fdMiningId");

		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdPlanYear", fdPlanYear);
		_map.put("fdPlanMonth", fdPlanMonth);
		_map.put("fdMiningId", fdMiningId);
		
		List result = ProducePlan.goback(_map);
		boolean canBack = true;
		
		if(result != null && result.size() > 0) {
			for(int i = 0; i < result.size(); i++) {
				ZMCPProducePlan plan = (ZMCPProducePlan)result.get(i);
				if(plan.getFdPlanStatus().equals("生效")) {
					canBack = false;
				}
			}
			
			if(!canBack) {
				inInfo.setStatus(-1);
				inInfo = this.query(inInfo);
				inInfo.setMsg(fdPlanYear +"年"+ fdPlanMonth +"月的生产计划已经整体发布，不能撤回！");
				return inInfo;
			}
			
			//2.0删除生产计划中，从表的数据
			String fdProfessionalplanId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");
			ProducePlanOther.goback(fdProfessionalplanId, "ZMCPProducePlanZC.goback");
			ProducePlanOther.goback(fdProfessionalplanId, "ZMCPProducePlanZK.goback");
			ProducePlanOther.goback(fdProfessionalplanId, "ZMCPProducePlanGLAZ.goback");
		}
		
		//3.0更改专业计划的状态为草拟
		Map<String, String> params = new HashMap<String, String>();
		params.put("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		params.put("fdPlanStatus", "上报");
		
		int rowcount = dao.update("ZMCPProfessionalPlan.goback", params);
		
		EiInfo out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;
	}
	
	/**
	 * <p>
	 * Function: validate
	 * </p>
	 * <p>
	 * Description: 对主表记录新增，删除，上报前的后台校验
	 * </p>
	 */
	@SuppressWarnings("rawtypes")
	private boolean validate(ZMCPProfessionalPlan _dom, String sqlName, Map<String, String> params, String type) {
		if (params == null) {
			params = new HashMap<String, String>();
		}
		List result = dao.query(sqlName, params);
		if (result != null && result.size() > 0 && !"report".equals(type)) {
			return true;
		}
		return false;
	}
	@SuppressWarnings("unchecked")
	public EiInfo copy(EiInfo inInfo) {
		// 查找表中的最近 年份+月份
		String fdMiningId = UserSession.getInSessionProperty("miningCode")
				.toString();
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdMiningId", fdMiningId);
		_map.put("fdPlanType", "抽采计划");
		List<ZMCPProfessionalPlan> list = dao.query(
				"ZMCPProfessionalPlan.query", _map);
		ZMCPProfessionalPlan zm = (ZMCPProfessionalPlan) list.get(0);

		String year = zm.getFdPlanYear() == null ? StaticTools.getYear() : zm
				.getFdPlanYear().trim();
		String month = zm.getFdPlanMonth() == null ? StaticTools.getMonth()
				: zm.getFdPlanMonth().trim();

		String oldKeyId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");

		// 处理年份和月份
		if (Integer.parseInt(month) >= 12) {
			month = "01";
			year = String.valueOf(Integer.parseInt(year) + 1);
		} else {
			month = String.valueOf(Integer.parseInt(month) + 1);
			if (month.length() == 1) {
				month = "0" + month;
			}
		}

		// 添加主表信息给复制行信息 -- 插入
		String fdProfessionalplanId = TablePk.getInstance().getNextValue(
				"T_CP_PROFESSIONALPLAN");
		inInfo.getBlock("result").setCell(0, "fdPlanYear", year);
		inInfo.getBlock("result").setCell(0, "fdPlanMonth", month);
		inInfo.getBlock("result").setCell(0, "fdKeyId", fdProfessionalplanId);
		inInfo.getBlock("result").setCell(0, "fdPlanStatus", "草拟");
		inInfo.getBlock("result").setCell(0, "fdTitle",
				year + "年" + month + "月的抽采计划");

		inInfo.getBlock("result").setCell(0, "fdCreateDate",StaticTools.getDate());
		inInfo.getBlock("result").setCell(0, "fdCreatorId",UserSession.getUserId().toString());
		inInfo.getBlock("result").setCell(0, "fdCreator",UserSession.getInSessionProperty("UserCname").toString());
		inInfo.getBlock("result").setCell(0, "fdCreateDepartmentId",UserSession.getInSessionProperty("orgCode").toString());
		inInfo.getBlock("result").setCell(0, "fdCreateDepartment",UserSession.getInSessionProperty("orgName").toString());
	//不设置fdBhcsl、fdZhcsl报错
		inInfo.getBlock("result").setCell(0, "fdBhcsl", null);
		inInfo.getBlock("result").setCell(0, "fdZhcsl", null);
		inInfo.getBlock("result").setCell(0, "fdPulisherId", null);
		inInfo.getBlock("result").setCell(0, "fdPulisher", null);

		super.insert(inInfo, "ZMCPProfessionalPlan.insert", "result");

		// 获取选取记录的ID
		Map<String, String> map = new HashMap<String, String>();
		map.put("fdProfessionalplanId", oldKeyId);
		map.put("isProfessionalplan", "任意数值");
		//钻尺
		List<ZMCPProducePlanZC> CMlist = dao.query("ZMCPProducePlanZC.query",
				map);
		for (int i = 0; i < CMlist.size(); i++) {
			ZMCPProducePlanZC zmcp = CMlist.get(i);
			zmcp.setFdKeyId(TablePk.getInstance().getNextValue(
					"ZMCPProducePlanZC"));
			zmcp.setFdProfessionalplanId(fdProfessionalplanId);
			dao.insert("ZMCPProducePlanZC.insert", zmcp.toMap());
		}
		//零星
		List<ZMCPProducePlanZK> CMlist2 = dao.query("ZMCPProducePlanZK.query",
				map);
		for (int i = 0; i < CMlist2.size(); i++) {
			ZMCPProducePlanZK zmcp = CMlist2.get(i);
			zmcp.setFdKeyId(TablePk.getInstance().getNextValue(
					"ZMCPProducePlanZK"));
			zmcp.setFdProfessionalplanId(fdProfessionalplanId);
			dao.insert("ZMCPProducePlanZK.insert", zmcp.toMap());
		}
		//管道
		List<ZMCPProducePlanGLAZ> CMlist3 = dao.query("ZMCPProducePlanGLAZ.query",
				map);
		for (int i = 0; i < CMlist3.size(); i++) {
			ZMCPProducePlanGLAZ zmcp = CMlist3.get(i);
			zmcp.setFdKeyId(TablePk.getInstance().getNextValue(
					"ZMCPProducePlanGLAZ"));
			zmcp.setFdProfessionalplanId(fdProfessionalplanId);
			dao.insert("ZMCPProducePlanGLAZ.insert", zmcp.toMap());
		}
		EiInfo out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作 记录成功");
		return out;
	}

	@SuppressWarnings("rawtypes")
	private boolean validateModify(EiInfo inInfo, String sqlName, Map<String, String> params, String type) {
		if (params == null) {
			params = new HashMap<String, String>();
		}
		List result = dao.query(sqlName, params);
		if (result != null && result.size() > 0 && !"report".equals(type)) {
			if (type.equals("insert")) {
				String msg = "该年月的抽采专业计划已经存在！";
				inInfo.setMsg(msg);
			} else if (type.equals("delete")) {
				String msg = "该抽采专业包含详细计划，不可删除！";
				inInfo.setMsg(msg);
			} else if (type.equals("update")) {
				String msg = "该抽采专业包含详细计划，不可修改！";
				inInfo.setMsg(msg);
			}
			inInfo.setStatus(-1);
			return true;
		}
		return false;
	}
}
